import React, { useEffect, useContext, useRef, useCallback, ReactText } from 'react';
import { Form } from 'antd';
import { useForm } from 'antd/lib/form/Form';
import { InspectorContext } from '../FlowManage';
import {
  FetchDataParam,
  FetchDataResponse,
  FetchRecordResponse,
  PageSelect,
} from 'components/UILibrary/pageSelect';
import { getSmsTempInfo, getSmsTempList } from 'admin/servers/servers';
import { CustomFormItemsHoc } from './CustomFormHoc';

/**
 * 结束语组件
 * 示例： AI管理-机器人管理-版本管理-配置话术流程-结束组件
 */
const EndComponent: React.FC = () => {
  const [form] = useForm();
  const smsSelectRef = useRef<any>();
  const { selectedData, onInputChange, isView } = useContext(InspectorContext);

  const { Input, TextArea, Switch } = CustomFormItemsHoc({ disabled: isView });

  const initForm = useCallback(() => {
    console.log('✅form数据-结束语组件-selectedData', selectedData);
    form.setFieldsValue(selectedData);
    if (selectedData.smsTemplateId) {
      // 触发onChange事件
      smsSelectRef.current?.setValue(selectedData.smsTemplateId);
    }
  }, [form, selectedData]);
  useEffect(() => {
    // 需要手动设置form数据, initialValue初始化属性在切换同组件的props数据时不会更新
    initForm();
    setTimeout(() => {
      // 表单验证
      form.validateFields();
    }, 0);
  }, [form, initForm]);
  const fetchSmsTempList = (args: FetchDataParam): FetchDataResponse => {
    return new Promise(resolve => {
      getSmsTempList({
        pageNo: args.pageNum,
        pageSize: args.pageSize,
        templateName: args.keywords,
      })
        .then(res => {
          resolve({
            data: res.data?.map(item => {
              return {
                label: item.templateName,
                value: item.templateId,
              };
            }),
            total: res.count as number,
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  };
  /**
   * pageSelect setValue时查记录的函数:根据id
   */
  const fetchSmsTempRecord = (templateId: ReactText): FetchRecordResponse => {
    return new Promise(resolve => {
      getSmsTempInfo(templateId as number)
        .then(res => {
          const item = res.data;
          resolve({
            label: item.templateName,
            value: item.templateId,
            data: item, // 便于onChange判断，有data则回显赋值不用更新数据
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  };

  return (
    <>
      <Form layout="vertical" form={form}>
        <Form.Item
          label="结束语组件名称"
          name="title"
          rules={[
            {
              required: true,
              whitespace: true,
              max: 10,
              message: '仅支持输入10个以内字符',
            },
          ]}
          getValueFromEvent={event => {
            return event.target.value.replace(/\s+/g, '');
          }}
        >
          <Input
            maxLength={10}
            onBlur={(e: any) => {
              onInputChange('title', e.target.value, e.type === 'blur');
            }}
          />
        </Form.Item>
        <Form.Item
          label="话术内容"
          name="script"
          rules={[
            {
              required: true,
              whitespace: true,
              max: 500,
              message: '仅支持输入500个以内字符',
            },
          ]}
          getValueFromEvent={event => {
            return event.target.value.replace(/\s+/g, '');
          }}
        >
          <TextArea
            maxLength={500}
            onBlur={(e: any) => {
              onInputChange('script', e.target.value, e.type === 'blur');
            }}
          />
        </Form.Item>
        {/* <Form.Item label="短信设置">
          <Switch
            defaultChecked={selectedData.smsSwitch === 'on'}
            onChange={(status: boolean) => {
              onInputChange('smsSwitch', status ? 'on' : 'off', true);
              if (!status) {
                // 关闭时，需要清空短信模板id
                onInputChange('smsTemplateId', undefined, true);
              }
            }}
          />
        </Form.Item>
        {selectedData.smsSwitch === 'on' && (
          <Form.Item name="smsTemplateId" rules={[{ required: true, message: '请选择短信模板' }]}>
            <PageSelect
              disabled={isView}
              allowClear
              key="smsSelect"
              ref={smsSelectRef}
              fetchData={fetchSmsTempList}
              placeholder="请选择短信模板"
              fetchRecord={fetchSmsTempRecord}
              onChange={(val, data) => {
                if (!data) {
                  console.log('data无值---赋值更新数据', val, data);
                  onInputChange('smsTemplateId', val, true);
                }
              }}
            />
          </Form.Item>
        )} */}
      </Form>
    </>
  );
};

export default EndComponent;
